package com.hadoop.practice.donglog;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * User: wujun
 * Date: 14-5-27 上午11:01
 */
public class LogFormatUtils {
    /**
     * 175.44.30.93 - - [29/Sep/2013:00:10:16 +0800] "GET /structure/heap/ HTTP/1.1" 200 22539 "-" "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1;)"
     * 175.44.19.36 - - [29/Sep/2013:00:10:18 +0800] "GET /mapreduce-nextgen/client-codes HTTP/1.1" 301 422 "http://dongxicheng.org/mapreduce-nextgen/client-codes/" "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;
     * 上面给出了两条访问日志，每条占一行，每一行有多个字段，字段之间用空格分隔，以第一行为例：“175.44.30.93”为访问机器的IP， “[29/Sep/2013:00:10:16 +0800]”是访问时间，"GET /structure/heap/ HTTP/1.1"中“/structure/heap/”是访问的网站子目录，即访问的页面为“http://dongxicheng.org/structure/heap/”，其他字段含义可暂时不关注，每一行字段数目是相同且规整的。
     */
    private static final String LOG_REGEX =
            "^([\\d.]+) (\\S+) (\\S+) \\[([\\w\\/:]+\\s[+\\-]\\d{4})] \"(.+?)\" (\\d+) (\\d+) \"([^\"]+)\" \"([^\"]+)\"";
    private static final  int  NUM_FIELDS =  9 ;

    public static Matcher init(String logEntryLine) {
        Pattern p = Pattern.compile ( LOG_REGEX ) ;
        Matcher matcher = p.matcher ( logEntryLine ) ;
        if  ( !matcher.matches ()  ||
                NUM_FIELDS != matcher.groupCount ()) {
            System.err.println ( "Bad log entry (or problem with RE?):" ) ;
            System.err.println ( logEntryLine ) ;
            return null;
        }
        return matcher;
    }

    public static String getVistorIp(String log) {
        Matcher matcher = init(log);
        if (matcher == null) {
            return null;
        }
        return matcher.group(1);
    }

    public static String getRequestDir(String log) {
        Matcher matcher = init(log);
        if (matcher == null) {
            return null;
        }
        return matcher.group(5).split(" ")[1];
    }
}
